package com.moleq.mgpos.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.moleq.adapter.FlipChartAdapter;
import com.moleq.adapter.ItemListAdapter;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.device.BaseScanner;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.ScannerSetting;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.logic.UPC;
import com.moleq.mgpos.activities.PriceSettingActivity.SP;
import com.moleq.models.FlipChart;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ItemSetting;
import com.moleq.service.FlipChartService;
import com.moleq.service.ItemPicService;
import com.moleq.service.ItemSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.util.ImageUtil;
import com.moleq.util.MoleQUtil;

public class FlipChartSettingActivity extends MoleQBaseActivity {
	
//	private DBHelper dbHellper = null;
	private Spinner sp_list;
	private String[] sp_items;
	private EditText et_search;
	private Button btn_search,btn_exit;
	private TextView tv_page;
	private ImageButton ibtn_next,ibtn_backpage,ibtn_nextpage;
	
	private TextView tv_dupc,tv_dname,tv_ddesc,tv_dprice;
	private ImageView iv_photo;
	
	private List<ItemSetting> itemlist = null;
	private List<FlipChart> listflipChart = null;
	private ItemListAdapter itemAdapter;
	private FlipChartAdapter flipAdapter;
	private ListView lv_items;
	private static ListView lv_chart;
	private ArrayList<EditText> ets = new ArrayList<EditText>();
	
	private LinearLayout ll_middle,ll_right;
	
	private int searchType = 0;
	private String searchString = "";
	private int PageCountSize = 0;
	
	private DeviceSettingService mSettingService;
	private FlipChartService flipChartService;
	private ItemPicService mItemPicService;
	private ItemSettingService itemservice = null;
	private DeviceManager mDeviceManager;
	private MessageDialog mMessageDialog;
	private boolean result = false;
	
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_flipchart_setting);
        
      //=========== setup scanner =================
  		mDeviceManager = DeviceManager.getInstance();
  		mSettingService = ServiceManager.getInstance().mDeviceSettingService;
  				
  		List<ScannerSetting> scannerSettings = mSettingService.getScannerSettings();
  					
  		// check scanner
  		int iScannerCount = scannerSettings.size();
  		for (int i = 0; i < iScannerCount; i++) {
  			int iPort = scannerSettings.get(i).getPort();
  			for (int j = i+1; j < iScannerCount; j++) {
  				if (iPort == scannerSettings.get(j).getPort()) {
  					ShowMessage(" Scanner setup error. Please check.",
  							mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
  					finish();
  				}

  			}
  		}
  		
  		for(int i = 0;i<scannerSettings.size();i++){
  			BaseScanner baseScanner = new BaseScanner();
  			 baseScanner.setScannerSetting(scannerSettings.get(i));
  			 mDeviceManager.addScanner(baseScanner);
  		}
  		
  		// open scanner
  		for(int i= 0 ; i <mDeviceManager.scanners.size();i++){
  			mDeviceManager.scanners.get(i).onConnect();
  			mDeviceManager.scanners.get(i).setCallbackEvent(this);
  			mDeviceManager.scanners.get(i).onEnableScanner();
  		}
  		
  		
  		//============================================
        
        sp_list = (Spinner) findViewById(R.id.sp_condition);
        sp_items = getResources().getStringArray(R.array.sp_condition_name);
        ArrayAdapter<String> SpAdapter = new ArrayAdapter<String>(this,
        		android.R.layout.simple_spinner_item, sp_items);
        SpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_list.setAdapter(SpAdapter);
        sp_list.setOnItemSelectedListener(onItemSelectedListener);
        
        et_search = (EditText) findViewById(R.id.et_search);
        btn_search = (Button) findViewById(R.id.btn_search);
        btn_exit = (Button) findViewById(R.id.btn_exit);
        ibtn_next = (ImageButton) findViewById(R.id.ibtn_next);
        
        ibtn_backpage = (ImageButton) findViewById(R.id.ibtn_backpage);
        ibtn_nextpage = (ImageButton) findViewById(R.id.ibtn_nextpage);
        tv_page = (TextView) findViewById(R.id.tv_page);
        
        lv_items = (ListView) findViewById(R.id.lv_item);
        lv_chart = (ListView) findViewById(R.id.lv_chart);
        ll_middle = (LinearLayout) findViewById(R.id.ll_middle);
        ll_right = (LinearLayout) findViewById(R.id.ll_right);
        
        tv_dupc = (TextView) findViewById(R.id.tv_dupc);
        tv_dname = (TextView) findViewById(R.id.tv_dname);
        tv_ddesc = (TextView) findViewById(R.id.tv_ddesc);
        tv_dprice = (TextView) findViewById(R.id.tv_dprice);
        iv_photo = (ImageView) findViewById(R.id.iv_photo);
        
        btn_search.setOnClickListener(onClickListener);
        btn_exit.setOnClickListener(onClickListener);
        ibtn_next.setOnClickListener(onClickListener);
        
        ibtn_backpage.setOnClickListener(onClickListener);
        ibtn_nextpage.setOnClickListener(onClickListener);
        
        flipChartService = ServiceManager.getInstance().mFlipChartService;
        itemservice = ServiceManager.getInstance().mItemSettingService;
        mItemPicService = ServiceManager.getInstance().mItemPicService;
        DataBinding();
        lv_items.setOnItemClickListener(onItemClickListener);
        lv_chart.setOnItemClickListener(onItemClickListener);
        
        ll_middle.setOnClickListener(onClickListener);
        ll_right.setOnClickListener(onClickListener);
        tv_page.setText(String.valueOf(1));
        SetEnabledTrue();
    }
    public OnItemClickListener onItemClickListener = new OnItemClickListener() {


		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			switch(parent.getId()){
			case R.id.lv_item:
				Keyboard();
				itemAdapter.ScrollToRow(position);
				RefresItem(position);
				break;
			case R.id.lv_chart:
				flipAdapter.ScrollToRow(position);
				break;
			}
		}
	};
	
    public OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view, int position,
				long id) {
			if(sp_items[position].equals("ALL")){
				et_search.setEnabled(false);
			}else{
				et_search.setEnabled(true);
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			
		}
	};
	
	public OnClickListener onClickListener = new OnClickListener() {
		public void onClick(View view) {
			String pagetext = "";
			int page;
			
			switch (view.getId()) {
			case R.id.ibtn_backpage:
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page-1));
				BindingData((page - 2), searchType, searchString);
				SetPage();
				itemAdapter.ScrollToRow(0);
				break;
			case R.id.ibtn_nextpage:
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page+1));
				BindingData(page, searchType, searchString);
				SetPage();
				itemAdapter.ScrollToRow(0);
				break;
			case R.id.ll_right:
				Keyboard();
				break;
			case R.id.ll_middle:
				Keyboard();
				break;
			case R.id.btn_search:
				Keyboard();
				String search = et_search.getText().toString();
				if (search.equals("")) {
					return;
				}
				
				tv_page.setText(String.valueOf(1));
				Search();
				et_search.setText("");	
				break;
			case R.id.ibtn_next:
				Keyboard();
				FlipChart fc = new FlipChart();
				
				int index = itemAdapter.GetSelectedIndex();
				
				String upc = itemlist.get(index).getUpc();
				int fcCountMax = ServiceManager.getInstance().mPosSettingService.getPosSettingFCCount();
				if (flipChartService.GetCountFC() >= fcCountMax) {
					ShowMessage("The maximum number of items in the flip chart is " + fcCountMax + ".",
							mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
					return;
				}
				
				if (flipChartService.checkFlipChartInList(upc) == false) {
					fc.setId(flipChartService.getMaxId());
					fc.setUpc(upc);
					
					if (itemlist.get(index).getName().length() > 18) {
						fc.setName(itemlist.get(index).getName().substring(0, 17));
					}else {
						fc.setName(itemlist.get(index).getName());	
					}
					fc.setGroup(1);
					fc.setOrder(flipChartService.getMaxOrder() + 1);
					fc.setCreateTime(getDateTime());
					fc.setUpdateTime(getDateTime());
					
					listflipChart.add(fc);
					
					result = flipChartService.insertFlipChart(fc);
					if (GlobalInfo.getInstance().isMGNetwork) {
						mMGCreateFiles.createrFile(fc.toMGData("INSERT"));
					}
					ShowMessage(result);
					
					listflipChart = flipChartService.getAllFlipChart();
					ets.clear();
					
					flipAdapter.setSource(listflipChart);
					flipAdapter.notifyDataSetChanged();
					
					 
					flipAdapter.ScrollToRow(listflipChart.size() - 1);
					lv_chart.setSelection(lv_chart.getAdapter().getCount()-1);
				}else {
					ShowMessage("The item is already in the list.",
							mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
				}	
				break;
			case R.id.btn_exit:
				ShowMessage(getResources().getString(R.string.msg_exit_program),
					mMessageDialog.MESSAGE_BOX_YES_NO,mMessageDialog.ICON_INFO);
				break;
			default:
				break;
			}
		}
	};
	
	public void SetPage(){
		ibtn_backpage = (ImageButton) findViewById(R.id.ibtn_backpage);
		ibtn_nextpage = (ImageButton) findViewById(R.id.ibtn_nextpage);
		tv_page = (TextView) findViewById(R.id.tv_page);
		String pagetext = (String) tv_page.getText();
		int page = Integer.valueOf(pagetext);
		if (PageCountSize > page) {
			ibtn_nextpage.setEnabled(true);
			ibtn_nextpage.setVisibility(View.VISIBLE);
		}else {
			ibtn_nextpage.setEnabled(false);
			ibtn_nextpage.setVisibility(View.INVISIBLE);
		}
		
		if(PageCountSize > 1 && page > 1) {
			ibtn_backpage.setEnabled(true);
			ibtn_backpage.setVisibility(View.VISIBLE);
		}else {
			ibtn_backpage.setEnabled(false);
			ibtn_backpage.setVisibility(View.INVISIBLE);
		}
	}
	public void DataBinding(){		
		
		listflipChart = flipChartService.getAllFlipChart();
		if(flipAdapter == null)
			flipAdapter = new FlipChartAdapter(this, listflipChart);
		lv_chart.setAdapter(flipAdapter);
	}
	
	public void Search() {
		et_search = (EditText) findViewById(R.id.et_search);
		 searchString = et_search.getText().toString();
//		
//		String sql = "";
//		String countSql = "select count(F01) from t_item_setting as a,t_uom_desc as b where a.F23 = b.F23 ";
		switch ((int) sp_list.getSelectedItemId()) {
	
		case SP.UPC:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = flipChartService.UPC;
				if (searchString.length() < 14) {
					UPC upc = new UPC(searchString, UPC.INPUT_BY_MANUAL,
							GlobalInfo.getInstance().isNormalize);
					searchString = upc.code;
				}
				PageCountSize = itemservice.GetPageCountSize(
						searchType, searchString);
				if (BindingData(0, searchType, searchString) == false) {
					ShowMessage("Item Not Found.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					//SetEnabledFalse();
				}
				//ControlEmpty();
				SetPage();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.SubDepartment:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = flipChartService.SubDept;
				if (MoleQUtil.isNumeric(searchString)) {
					PageCountSize = itemservice.GetPageCountSize(
							searchType, searchString);
					if (BindingData(0, searchType, searchString) == false) {
						ShowMessage("Item Not Found.",
								MessageDialog.MESSAGE_BOX_OK,
								MessageDialog.ICON_INFO);
						//SetEnabledFalse();
					}
					SetPage();
				} else {
					if (itemlist != null) {
						itemlist.clear();
					}
				}
				//ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.Department:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = flipChartService.Department;
				if (MoleQUtil.isNumeric(searchString)) {
					PageCountSize = itemservice.GetPageCountSize(
							searchType, searchString);
					if (BindingData(0, searchType, searchString) == false) {
						ShowMessage("Item Not Found.",
								MessageDialog.MESSAGE_BOX_OK,
								MessageDialog.ICON_INFO);
						//SetEnabledFalse();
					}
					SetPage();
				} else {
					if (itemlist != null) {
						itemlist.clear();
					}
				}
				//ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		}

	}
	
	public boolean BindingData(int page, int SPType, String searchString) {
		if (itemlist == null) {
			itemlist = new ArrayList<ItemSetting>();
			itemlist = itemservice.SearchItems(page, SPType,
					searchString);

			itemAdapter = new ItemListAdapter(this, itemlist);
			lv_items.setAdapter(itemAdapter);
			if (itemlist.size() > 0) {
				tv_page.setVisibility(View.VISIBLE);

				RefresItem(0);
				ibtn_next.setEnabled(true);
				return true;
			} else {
				tv_page.setVisibility(View.INVISIBLE);
				ibtn_next.setEnabled(false);
				tv_dupc.setText("");
				tv_dname.setText("");
				tv_ddesc.setText("");
				tv_dprice.setText("");
				Bitmap bp = mItemPicService.getImageByUPC("");
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(FlipChartSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
//				setempty();
//				et_cp_amt.setText("");
//				et_cp_price.setText("");
//				InitializeEnabledFalse();
				return false;
			}
		} else {
			itemlist.clear();
			itemlist = itemservice.SearchItems(page, SPType,
					searchString);
			itemAdapter.setSource(itemlist);
			itemAdapter.notifyDataSetChanged();
			if (itemlist.size() > 0) {
				tv_page.setVisibility(View.VISIBLE);
				// int index = itemAdapter.GetSelectedIndex();
				RefresItem(0);
				ibtn_next.setEnabled(true);
				return true;
			} else {
				tv_page.setVisibility(View.INVISIBLE);
				ibtn_next.setEnabled(false);
				tv_dupc.setText("");
				tv_dname.setText("");
				tv_ddesc.setText("");
				tv_dprice.setText("");
				Bitmap bp = mItemPicService.getImageByUPC("");
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(FlipChartSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
//				setempty();
//				et_cp_amt.setText("");
//				et_cp_price.setText("");
//				InitializeEnabledFalse();
				return false;
			}
		}
	}

	public void RefresItem(int position) {
		String upc = null;

		if (itemlist != null) {
			upc = itemlist.get(position).getUpc();
			tv_dupc.setText(upc);
			tv_dname.setText(itemlist.get(position).getName());
			tv_ddesc.setText(itemlist.get(position).getDesc());
			String priceText = "";
			if (itemlist.get(position).getMultple() > 1) {
				priceText = String.valueOf(itemlist.get(position).getMultple()) + "/";
			}
			tv_dprice.setText(priceText+String.format("%.2f",itemlist.get(position).getPrice()));
			Bitmap bp = mItemPicService.getImageByUPC(upc);
			if (bp == null) {
				Bitmap logo = BitmapFactory.decodeResource(FlipChartSettingActivity.this
						.getApplicationContext().getResources(),
						R.drawable.moleqlogo);
				iv_photo.setImageBitmap(logo);
			} else {
				iv_photo.setImageBitmap(bp);
			}
			itemAdapter.ScrollToRow(position);
//			RefresItemPrice(upc);

//			InitializeEnabledTrue();
		}

	}
	
	public class SP {
		public static final int Department = 0;
		public static final int SubDepartment = 1;
		public static final int UPC = 2;
		// public static final int ALL = 0;
	}
	
	public String repeatString(String s, int n) {
		return String.format(String.format("%%0%dd", n), 0).replace("0", s);
	}
	
	public boolean isNumeic(String str){
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}
	
	public void DeleteMessage(int msg){
		switch(msg){
		case 0:
			ShowMessage("Delete Error.",
						mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
			break;
		case 1:
			break;
		}
	}
	
	public void showDeleteMessage(boolean re){
		if (re == false) {
			ShowMessage("Delete Error.",
					mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
		}
	}
		
	public void UpdateMessage(int msg){
		switch(msg){
		case 0:
			ShowMessage("Save Error.",
					mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
			break;
		case 1:
			break;
		}
	}
	
	public void ShowMessage(boolean re){
		if (re == false) {
			ShowMessage("Save Error.",
					mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
		}
	}
	
	public void ShowMessage(String ls_msg,int style,int icon){
		mDeviceManager.disableAllScanner();
		mMessageDialog = new MessageDialog(FlipChartSettingActivity.this);
		mMessageDialog.setStyle(style);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(ls_msg);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}
	
	public String getDateTime(){
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date(System.currentTimeMillis());
		String str = formatter.format(curDate);
		return str;
	}
	public void SetEnabledTrue(){
		ibtn_next.setEnabled(false);
		ibtn_backpage.setEnabled(false);
		ibtn_nextpage.setEnabled(false);
		ibtn_backpage.setVisibility(View.INVISIBLE);
		ibtn_nextpage.setVisibility(View.INVISIBLE);
		tv_page.setVisibility(View.INVISIBLE);
	}
	
	public void Keyboard(){
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(FlipChartSettingActivity.this
				.getCurrentFocus().getWindowToken(), 
				InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	//=========== setup scanner =================
	public void onErrorEvent(String res) {
		// TODO Auto-generated method stub
		
	}
	public void onScannerEvent(String res) {
		sp_list.setSelection(SP.UPC);
		et_search.setText(res);
		Keyboard();
		tv_page.setText(String.valueOf(1));
		this.Search();
		et_search.setText("");		
	}
	public void onTimeOutEvent() {
		// TODO Auto-generated method stub
		
	}
	public void onWeightEvent(int arg0) {
		// TODO Auto-generated method stub
		
	}	
	public static void set_lv_chart_Selection(int index){
		lv_chart.setSelection(index);
	}
	
	public void OpenScanner(){
		for(int i= 0 ; i <mDeviceManager.scanners.size();i++){
			mDeviceManager.scanners.get(i).onEnableScanner();
		}
	}
	
	public void CloseScanner(){
		for(int i= 0 ; i <mDeviceManager.scanners.size();i++){
			mDeviceManager.scanners.get(i).onDisableScanner();
		}
	}
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener(){

		public void onClickYes() {
			// TODO Auto-generated method stub
			mDeviceManager.disableAllScanner();
			mDeviceManager.disconnectAllScanner();
			mDeviceManager.resetALLDevices();
			finish();
		}

		public void onClickNo() {
			// TODO Auto-generated method stub
			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
			mMessageDialog.dismiss();
		}

		public void onClickOK() {
			// TODO Auto-generated method stub
			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
			mMessageDialog.dismiss();
		}
		
	};
	
	@Override
	public void onDataEvent(Object obj) {
		// TODO Auto-generated method stub
		
	}
	
}